import json
import json
import os.path
import random
from datetime import datetime

from flask import (
    Blueprint, request, session, current_app, send_from_directory
)

from .db import get_db
from.auth import login_required

bp = Blueprint('drawing', __name__, url_prefix='/drawing')


@bp.route('/text2img', methods=['GET', 'POST'])
# @login_required
def text2img():
    cur = get_db()
    if request.method == 'GET':
        UID = session.get("UID")
        if UID is None:
            UID = 10000
        return send_from_directory(os.path.join(current_app.root_path, 'static'), 'drawing.html')

    if request.method == 'POST':
        json_raw = request.get_json()
        UID = session.get('UID')
        if UID is None:
            UID = 10000
        task_ID = random.randint(1, 1000000)
        # cur.execute(f"INSERT INTO drawing VALUES ({UID},null,'{datetime.now()}',{task_ID})")
        cur.execute(f"INSERT INTO drawing_task_queue VALUES (%s,null,%s,null,%s,null,%s,null,null,%s)",
                    (task_ID, 'in queue', json.JSONEncoder().encode(json_raw), datetime.now(), UID)
                    )
        return {"task_ID": task_ID}


@bp.route('/progress', methods=['POST'])
# @login_required
def get_progress():
    cur = get_db()
    task_ID = request.json['task_ID']
    cur.execute(f"SELECT percentage FROM drawing_task_queue WHERE task_ID='{task_ID}'")
    return {
        "progress": cur.fetchone()[0]
    }

